package ac.il.technion.cs236635.project.core;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

import ac.il.technion.cs236635.project.core.server.ServerJob;

public class WatchDog implements Runnable {

	private volatile boolean finished = false;
	
	private int timeToWait = 5000;
	
	private Logger log = Logger.getLogger( WatchDog.class);
	
	public WatchDog( ) {
		Properties properties = new Properties( );
		try {
			properties.load( WatchDog.class.getClassLoader().getResourceAsStream( "client.properties"));
		} catch (IOException e) {
			log.error(e);
			return;
		}
		timeToWait = Integer.valueOf( properties.getProperty( "timeToWait", "5000"));
	}
	
	@Override
	public void run() {
		while ( !finished) {
			List<ServerJob> outdated = JobsKeeper.getInstance().findOutdated( );
			for( ServerJob job : outdated) {
				// In case there is too much time passed
				// need to resubmit jobs to the servers again.
				JobsSubmitted.getInstance().submit(job);
			}
			try {
				Thread.sleep( timeToWait);
			} catch (InterruptedException e) {
				log.error( e);
			}
		}
	}

	public void finish( ) {
		finished = true;
	}
}
